package logic

import (
	"baidu-dev/cache"
	"baidu-dev/models"
	"context"
	"errors"
	"fmt"
	"math/rand"

	"baidu-dev/baidurpc/baidurpc"
	"baidu-dev/baidurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *baidurpc.LoginRequest) (*baidurpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User

	user = models.User{
		Mobile:    in.Mobile,
		Password:  in.Password,
		NickName:  fmt.Sprintf("用户_%d", rand.Intn(10000)),
		HeadImage: "www.dsjakjd.com",
	}

	if err := user.FindByUserMobile(models.DB, in.Mobile); err != nil {
		return nil, errors.New("当前手机号未注册,请前往注册")
	}

	if in.LoginType == 1 {
		if in.Password != user.Password {
			return nil, errors.New("密码输入错误,请重新输入")
		}
	}

	if in.LoginType == 2 {
		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
		if result != in.SmsCode {
			return nil, errors.New("验证码输入错误,请重新输入")
		}
	}

	return &baidurpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
